package com.pjbao.Service;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

/**
 * java的各种类型之间的转换工具类
 * 
 * @author 邱鹏
 *
 */
public class TypeUtils {
	/**
	 * 将实体类对象转换成map对象
	 * 
	 * @param obj
	 * @return
	 */
	public static Map<String, Object> bean2Map(Object obj) {
		Map<String, Object> resultMap = null;
		if (obj == null) {
			resultMap = null;
		} else {
			resultMap = new HashMap<String, Object>();
			Field[] fields = obj.getClass().getDeclaredFields();
			try {
				for (int i = 0; i < fields.length; i++) {
					try {
						Field f = obj.getClass().getDeclaredField(fields[i].getName());
						f.setAccessible(true);
						Object o = f.get(obj);
						resultMap.put(fields[i].getName(), o);
					} catch (NoSuchFieldException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			}
		}
		return resultMap;
	}

	/**
	 * @return
	 */
	public static String date2Str() {
		return date2Str(null, "yyyy-MM-dd");
	}

	/**
	 * @param date
	 * @param fmt
	 * @return
	 */
	public static String date2Str(Date date, String fmt) {
		fmt = StringUtils.isNotEmpty(fmt) ? fmt : "yyyy-MM-dd HH:mm:ss";
		date = (date != null) ? date : new Date();
		DateFormat format = new SimpleDateFormat(fmt);
		return format.format(date);
	}
}
